GApp.AreaConfiguration = {
    attributesList: [],
    configurationsList: [],
    url: '/?url=configArea'
};

(function (P) {
    
///////////////////////////////////////////////////////////////////////////////
// AREA - ATTRIBUTES
///////////////////////////////////////////////////////////////////////////////
    
    P.getConfiguration = function (id) {
        var configuration = null;
        $.each(P.configurationsList, function (i, v) {
           if (v.id === id) {
               configuration = P.configurationsList[i];
           } 
        });
        return configuration;
    },
    
    P.updateAreaAttribute = function (idScheme, idArea, idAttribute, active) {
        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configArea/areaAttribute',
            data: {
                idScheme: idScheme,
                idArea: idArea,
                idAttribute: idAttribute,
                active: (active == true ? 1 : 0)
            }
        });
    },
    
    P.updateTableAttributes = function () {
        var tmp = [];
        var checkboxes = [];
        var id;
                
        $('#dataTables-attributes > tbody').html ('');
        $.each(GApp.AreaConfiguration.attributesList, function (i, v) {
            id = 'attr_' + v.id;
            
            tmp.push ('<tr class="odd gradeX">');
            tmp.push ('<td align="center">');
            tmp.push ('<input type="checkbox" id="' + id + '" ' + (v.active === '1' ? 'checked' : '') + '>');
            tmp.push ('</td>');
            tmp.push ('<td>' + v.name + '</td>');
            tmp.push ('<td>' + (v.order || 0) + '</td>');
            tmp.push ('</tr>');
            
            checkboxes.push (id);
        });

        $('#dataTables-attributes > tbody').html (tmp.join (''));
        
        if (checkboxes.length > 0) {
            var idScheme = $('#idScheme').val ();
            var idArea = $('#idArea').val ();
        
            $.each(checkboxes, function (i, v) {
                $('#' + v).on ('click', function () {
                    P.updateAreaAttribute (idScheme, idArea, 
                        v.replace ('attr_', ''), $(this).is(":checked"));
                });
            });
        }
    },
    
    P.updateTableConfigurations = function () {
        var tmp = [];
        var id;
                
        $('#dataTables-configurations > tbody').html ('');
        $.each(GApp.AreaConfiguration.configurationsList, function (i, v) {
            tmp.push ('<tr class="odd gradeX">');
            tmp.push ('<td align="center">');
            tmp.push ('<a href="#" onclick="GApp.AreaConfiguration.viewConfiguration (\'' + v.id + '\')">');
            tmp.push ('<i class="fa fa-gear fa-lg"></i></a> '); 
            tmp.push ('<a href="#" onclick="GApp.AreaConfiguration.modifyConfiguration (\'' + v.id + '\')">');
            tmp.push ('<i class="fa fa-pencil-square fa-lg"></i></a> '); 
            tmp.push ('<a href="#" onclick="GApp.AreaConfiguration.removeConfiguration (\'' + v.id + '\')">');
            tmp.push ('<i class="fa fa-minus-square fa-lg"></i></a>');
            tmp.push ('</td>');
            tmp.push ('<td>' + v.name + '</td>');
            tmp.push ('<td>' + (v.order || 0) + '</td>');
            tmp.push ('</tr>');
        });

        $('#dataTables-configurations > tbody').html (tmp.join (''));
    },
    
    P.updateListAttributes = function (url, doneCallback) {
         var idScheme = $('#idScheme').val ();
         var idArea = $('#idArea').val ();
         
         $.ajax ({
            type: 'get',
            url: GApp.baseURL + url,
            data: { 'idScheme': idScheme, 'idArea': idArea }
        })
        .done (function (data) {
            var json = JSON.parse (data);
            
            P.attributesList.length = 0;
            $.each (json.attributes || [], function (i, v) {
                P.attributesList.push (v);
            });

            if (doneCallback) {
                doneCallback.call (this);
            }
        })
        .fail (function () {
            console.log ('ERROR: updateTableAttributes');
        });
    }
    
    P.updateListConfigurations = function (url, doneCallback) {
         var idScheme = $('#idScheme').val ();
         var idArea = $('#idArea').val ();
         
         $.ajax ({
            type: 'get',
            url: GApp.baseURL + url,
            data: { 'idScheme': idScheme, 'idArea': idArea }
        })
        .done (function (data) {
            //var tmp = [];
            var json = JSON.parse (data);
            
            P.configurationsList.length = 0;
            $.each(json.configurations, function (i, v) {
                P.configurationsList.push (v);
            });
            
            if (doneCallback) {
                doneCallback.call (this);
            }
        })
        .fail (function () {
            console.log ('ERROR: updateTableAttributes');
        });
    },
    
    P.sendConfiguration = function (data, okCallback, errorCallback) {
        var url = ($('#configurationIdForm').val () !== '') 
            ? 'modifyConfiguration' : 'addConfiguration';
        var idScheme = $('#idScheme').val ();
        var idArea = $('#idArea').val ();

        $.ajax ({
            type: 'post',
            url: GApp.baseURL + P.url + '/' + url,
            data: {
                idScheme: idScheme,
                idArea: idArea,
                name: data.name,
                order: data.order,
                id: data.id
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.sendRemoveConfiguration = function (data, okCallback, errorCallback) {        
        $.ajax ({
            type: 'post',
            url: GApp.baseURL + '/?url=configArea/removeConfiguration',
            data: {
                id: data.id
            }
        })
        .done (function (data) {
            if (okCallback) {
                okCallback.call (this, data);
            }
        })
        .fail (function () {
            if (errorCallback) {
                errorCallback.call (this);
            }
        });
    },
    
    P.validateAndCommitModal = function () {
        var errors = 0;
        var configuration = {
            id: $('#configurationIdForm').val () || null,
            name: $('#configurationNameForm').val () || null,
            order: $('#configurationOrderForm').val ()
        };

        if (!configuration.name || configuration.name.length == 0) {
            $('#configurationNameForm').parent ().addClass ('has-error');
            errors++;
        }
        else {
            $('#configurationNameForm').parent ().removeClass ('has-error');
        }

        if (errors === 0) {
             P.sendConfiguration (configuration, 
                 function () {
                    // OK
                    $('#configurationModalDlg').modal ('hide');
                    //P.updateTableConfiguration (P.url);

                    var url = P.url + '/configurations';
                    P.updateListConfigurations (url, function () {
                        P.updateTableConfigurations ();
                    });
                 },
                 function () {
                    // Error
                    console.log  ('Error: validateAndCommitModal');
                 }
             );
        }
    },
    
    P.confirmFormConfiguration = function (configuration) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>¿Quieres eliminar la configuración seleccionada?</label>');
        form.push ('</div>');
        
        $('#configurationModalLabel').text ('Eliminar configuración');
        $('#configurationAcceptModalDlg').on ('click', function () {
           $('#configurationModalDlg').modal ('hide');
           GApp.Helper.showPleaseWait ();
           
           P.sendRemoveConfiguration (configuration, 
                 function () {
                    // OK
                    var url = GApp.AreaConfiguration.url + '/configurations';
                    GApp.AreaConfiguration.updateListConfigurations (url, function () {
                        GApp.AreaConfiguration.updateTableConfigurations ();
                        GApp.Helper.hidePleaseWait ();
                    });
                 },
                 function () {
                    // Error
                    console.log  ('Error: confirmFormCsonfiguration');
                    GApp.Helper.hidePleaseWait ();
                 }
            );
        });
        
        $('#configurationModalBody').html (form.join (''));
        $('#configurationModalDlg').modal ();
        $('#configurationModalDlg').on ('hidden.bs.modal', function () {
            $('#configurationAcceptModalDlg').off ('click');
            $('#configurationModalDlg').off ('hidden.bs.modal');
        });
        
        if (configuration) {
            $('#configurationIdForm').val (configuration.id);
        }
        
        return false;
    },
    
    P.showFormConfiguration = function (title, configuration) {
        var form = [];
        form.push ('<div class="form-group">');
        form.push ('<label>Nombre</label>');
        form.push ('<input class="form-control" placeholder="Nombre de la configuración" id="configurationNameForm">');
        form.push ('</div>');
        form.push ('<div class="form-group">');
        form.push ('<label>Orden</label>');
        form.push ('<input class="form-control" placeholder="Orden" id="configurationOrderForm">');
        form.push ('<input type="hidden" id="configurationIdForm">');
        form.push ('</div>');
        
        $('#configurationModalLabel').text (title);
        $('#configurationAcceptModalDlg').on ('click', function () {
           P.validateAndCommitModal ();
        });
        
        $('#configurationModalBody').html (form.join (''));
        $('#configurationModalDlg').modal ();
        $('#configurationModalDlg').on ('hidden.bs.modal', function () {
            $('#configurationAcceptModalDlg').off ('click');
            $('#configurationModalDlg').off ('hidden.bs.modal');
        });
        
        if (configuration) {
            $('#configurationNameForm').val (configuration.name);
            $('#configurationOrderForm').val (configuration.order);
            $('#configurationIdForm').val (configuration.id);
        }
        
        return false;
    },
    
    P.newConfiguration = function () {        
        return P.showFormConfiguration ('Nueva configuración');
    },
    
    P.modifyConfiguration = function (configurationId) {
        return P.showFormConfiguration ('Modificar configuración', P.getConfiguration (configurationId));
    },
    
    P.removeConfiguration = function (configurationId) {
        return P.confirmFormConfiguration (P.getConfiguration (configurationId));
    },
    
    P.viewConfiguration = function (idConfiguration) {
        var idScheme = $('#idScheme').val ();
        var idArea = $('#idArea').val ();
        var url = GApp.baseURL + '?url=configConfiguration';
        url += '&idScheme=' + idScheme;
        url += '&idArea=' + idArea;
        url += '&id=' + idConfiguration;
        
        window.location = url;
    }
} (GApp.AreaConfiguration));

if (document.URL.indexOf (GApp.AreaConfiguration.url + '&idScheme=') > 0) {
    GApp.Helper.createWaitDialog ('waitingModal');
    
    $(document).ready (function () {
        $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
            var target = $(e.target).attr("href");
            if ((target == '#areaConfigurations')) {
                GApp.AreaConfiguration.updateTableConfigurations ();
            }
            else if ((target == '#areaAttributes')) {
                GApp.AreaConfiguration.updateTableAttributes ();
            }
        });
        
        GApp.Helper.showPleaseWait ();
        
        var url = GApp.AreaConfiguration.url + '/attributes';
        GApp.AreaConfiguration.updateListAttributes (url, function () {
            url = GApp.AreaConfiguration.url + '/configurations';
            
            GApp.AreaConfiguration.updateListConfigurations (url, function () {
                GApp.AreaConfiguration.updateTableAttributes ();
                GApp.Helper.hidePleaseWait ();
            });
        });
    });
}
